
const zz = require('../utils/zz');
const render = require('../config/index');
module.exports = app => {

  const { validator } = app;

  validator.addRule('phone', (rule, value) => {
    if (!zz.phone.test(value)) {
      return '手机号格式错误';
    }
  });

  validator.addRule('password', (rule, value) => {
    if (value.length < 8 || value.length > 20) {
      return '密码格式错误';
    }
  });

  validator.addRule('email', (rule, value) => {
    if (!zz.email.test(value)) {
      return '邮箱格式错误';
    }
  });

  validator.addRule('renderList', (rule, value) => {
    if (!(value instanceof Array)) {
      return '需要数组类型';
    }
    if (value.length === 0) {
      return '数据为空';
    }
    const map = new Map();
    value.map(item => {
      if (map.has(item.type)) {
        map.set(item.type, map.get(item.type) + 1);
      } else {
        map.set(item.type, 1);
      }
      return item;
    });
    for (const key in render.allowNumber) {
      if (map.get(key) > render.allowNumber[key]) {
        return `${key}最多${render.allowNumber[key]}个`;
      }
    }
  });

  validator.addRule('content', (rule, value) => {
    if (!(value instanceof Array)) {
      return '需要数组类型';
    }
    if (value.length === 0) {
      return '内容不能为空';
    }
    for (let i = 0; i < value.length; i++) {
      if (value[i].ques === 0) {
        return '题目不能为空';
      }
    }
  });

};
